<template>
  <div>
    <HeadView />
    <div class="content register">
    <div class="flex r_head">
      <h4>{{title+'.web3'}}</h4>
      <div class="flex r_p">
        <p :class="{'up':type === 'register'}" @click="onTab('register')">Register</p>
        <p :class="{'up':type === 'details'}" @click="onTab('details')">Details</p>
      </div>
    </div>
    <div class="r_con">
      <CardView v-if="title" :disable="true" :title="title" />
      
      <div v-if="!isToken" v-show="type == 'register'" class="rc_right">
        <div class="rc_right_green">
          <div class="rc_title">REGISTER YOUR DOMAIN IN 3 STEPS</div>
          <ul>
            <li class="up">
              <span>1</span>
              <div>
                <h6>REQUEST TO REGISTER</h6>
                <p>You will be asked to submit the registration 
                request. Your request should be processed 
                within 7 days. Otherwise, you will have to 
                resubmit the registration request again.
                </p>
              </div>
            </li>

            <li :class="{'up':this.state == '2' || this.state == '3'}">
              <span>2</span>
              <div>
                <h6>WAIT FOR 60 SECONDS</h6>
                <p>The waiting time is to prevent other parties 
                from front-running you in the domain 
                registration.
                </p>
              </div>
            </li>

            <li :class="{'up':this.state == '3'}">
              <span>3</span>
              <div>
                <h6>CONFIRM YOUR REGISTRATION</h6>
                <p>You will obtain the domain once this 
                  transaction is completed. 
                </p>
              </div>
            </li>
          </ul>
        </div>
        <div class="rc_request">
          <div class="rc_equal">
            <div class="flex">
              <p>Registration Period</p>
              <p><i>99</i> Years</p>
            </div>
            <div class="flex">
              <p>Registration Price</p>
              <p v-if="this.price == 'Free'" class="green">
                {{this.price}}
              </p>
              <p v-else class="p_price">
                <i>{{this.price}}</i> USDT
                <span v-if="ethPrice">≈ {{(this.ethPrice / Math.pow(10,18)).toFixed(6)}} ETH</span>
              </p>
              
            </div>
            <div class="flex">
              <p>Gas Price</p>
              <p><i>0.005</i> ETH</p>
            </div>
            <div class="flex">
              <p>Tax</p>
              <p><i>0</i> USDT</p>
            </div>
          </div>
          <div class="rc_border">
            <div v-if="this.state == '1'" @click="signWeb3()" class="connect">Request</div>
            <el-button v-if="this.state == '2'" size="medium" type="primary" round :loading="true">Waiting</el-button>
            <div v-if="this.state == '3'" @click="onRegister()" class="connect">Register</div>
          </div>
        </div>
      </div>
      
      <div v-show="type == 'register'" v-if="isToken" class="rc_right rc_right_a">
        <!-- This name is already registered or cannot be registered -->
          <p>{{title+'.web3'}}</p>
          <div>This name is already taken or unAvailable</div>
      </div>

      <div v-show="type == 'details'" class="de_right">
        <div v-if="!isToken">
          <ul class="de_ul">
            <li>
              <p>Parent <span>web3</span></p>
            </li>
            <li>
              <p>Owner <span>None</span></p>
              <div @click="this.type = 'register'" class="connect">Register</div>
            </li>
          </ul>
          <img src="@/assets/img/book.svg" class="book" alt="" srcset="">
        </div>
        <div v-if="isToken">
          <TableView :disable="true" :address="address" />
        </div>
        <div v-else>

        </div>
      </div>
    </div>
  </div>
  <LinkView/>
  </div>
  
</template>

<script>
import HeadView from '@/components/HeadView.vue'
import CardView from '@/components/CardView.vue'
import TableView from '@/components/TableView.vue'
import { ElMessage } from 'element-plus'
import LinkView from '@/components/LinkView.vue'

export default {
  data(){
    return {
      // star:null,
      type:'register',
      price:0,
      title:null,
      num:5,
      second:3126340800,
      address:null,
      //contract4-
      contract4:'0xA2d6Bb256c9F3DecfE3618841852fF521fA405e6',
      state:'1',
      time:60,
      ethPrice:null,
      commitments:null,
      preCommit:null,
      isToken:false,
      isLoading:false,
    }
  },
  async mounted(){
    this.isToken = localStorage.getItem('state') && true
    console.log('this.isToken',this.isToken)
    this.address = localStorage.getItem('address') || null
    // this.star = this.$route.query.star || false
    console.log('this.star')
    console.log(this.star)
    if(this.isToken){
      this.type = 'details'
    }
    this.title = this.$route.query.title || null
    if(this.address && !this.isToken){
      this.getPrice(this.address)
      this.getPreCommit(this.address)
    }else{
      this.isToken = true
    }

  },
  
  methods:{
    async signWeb3(){

      if(this.isLoading){
        return
      }
      this.isLoading = true
      this.$loadinga()
        if(!this.address){
          this.$loadinga(true)
          this.isLoading = false
          alert(' Not address')
          return
        }
        // console.log(this.title,this.address,labelhash,this.contract4,this.address)
        console.log('this.preCommit')
        console.log(this.preCommit)
        if(this.preCommit){
          this.$utils.Tx(await window.contract7.methods.commit(this.preCommit),this.address,null,(res)=>{
            this.$loadinga(true)
            this.isLoading = false
            if(res){
              this.state = '2'
            }
            console.log(res)
          },(err)=>{
              this.$loadinga(true)
              this.isLoading = false
              // console.log(err)
              ElMessage.error(err)
          }) 
        }
    },
    async getPrice(address){
      if(window.contract7){
        console.log(address,this.title,this.second)
        try {
          let isEthPrice = await window.contract7.methods.rentPrice(address,this.title,this.second).call()
          console.log('isEthPrice')
          console.log(isEthPrice)
          if(isEthPrice == '0'){
            this.price = 'Free'
          }else{
            let index = this.title.length > this.num ? this.num:this.title.length
            let times = await window.contract6.methods.rentPrices(index - 1).call()
            this.price = (times * 3126340800 / (Math.pow(10,18))).toFixed(2)
            this.ethPrice = isEthPrice 
          }
        } catch (error) {
          console.log(error)
        }
      }
    },
    async getPreCommit(address){
      // this.$loadinga()
      try {
        // 
        let labelhash = window.web3js.utils.keccak256(this.title)
        this.preCommit = await window.contract7.methods.makeCommitmentWithConfig(this.title,address,labelhash,this.contract4,address).call()
        console.log('preCommit',this.preCommit)
        let commitments = await window.contract7.methods.commitments(this.preCommit).call()
        // this.$loadinga(true)
        if(commitments){
          let timestamp  = new Date().getTime()
          // console.log('timestamp')
          // console.log('当前时间',new Date(timestamp))
          // console.log('提交时间',new Date(parseInt(commitments+'000')))
          // console.log('commitments',commitments)
          // console.log((timestamp - parseInt(commitments+'000'))/60000)
          let times = timestamp - parseInt(commitments+'000')
          console.log('times',times)
          if(commitments == '0'){
            this.state = '1'
          }else if(times < 60000 && commitments != '0'){
            this.state = '2'
          }
          else if(times > 60000 && times < (60000 * 60 *24)){
            this.state = '3'
          }else if(times > (60000 * 60 *24)){
            this.state = '1'
          }
        }else{
          this.state = '1'
        }
        this.$loadinga(true)
      } catch (error) {
        this.$loadinga(true)
      }
      
    },
    async onRegister(){
      if(this.isLoading){
        return
      }

      this.isLoading = true
      // console.log(.toHex())
      this.$loadinga()
      let labelhash = window.web3js.utils.keccak256(this.title)
            // this.$loadinga(true)
              this.$utils.Tx(
                await window.contract7.methods.registerWithConfig(this.title,this.address,this.second,labelhash,this.contract4,this.address),
                this.address,
                this.ethPrice?window.web3js.utils.toHex(this.ethPrice):null,
                (res)=>{
                  this.$loadinga(true)
                  this.isLoading = false
                  if(res){
                    this.type = 'details'
                    this.isToken = true
                    localStorage.setItem('state','4')
                  }
                  console.log(res)
                },
                (err)=>{
                  console.log(err)
                  // alert(1)
                  this.$loadinga(true)
                  this.isLoading = false
                  ElMessage.error(err)
                  // console.log(err)
              })
            
      // let register = await window.contract7.methods.registerWithConfig(this.title,this.address,this.second,labelhash,this.contract4,this.address).call()
    },
    onTab(val){
      this.type = val
    }
  },
  watch: {
      state: {
          handler (newName) {
              if(newName == 2){
                let time = setTimeout(()=>{
                  clearTimeout(time)
                  this.state = '3'
                },60000)
              }
          },
          immediate: true
      },
      '$store.state.address':function(val){
        console.log('val')
        console.log(val)
        if(val){
          this.isToken = localStorage.getItem('state') && true
          this.address = val
          if(!this.isToken){
            this.getPrice(val)
            this.getPreCommit(val)
          }
        }
        if(!val){
          this.address = null
          this.isToken = true
        }
      }

  },
  components: {
    HeadView,
    CardView,
    TableView,
    LinkView
  }
}
</script>

<style lang="less" scoped>
  .p_price{
    position: relative;
    span{color: #aaa;position: absolute;top: 18px;right: 0;font-size: 12.5px;width: 120px;text-align: right;}

  }
</style>
